<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { MaterialSearchData, PaginationType } from "@/api/Material/params";
import { MaterialListResData, MaterialResData } from "@/api/Material/res";
import { getMaterialListApi, deleteMaterialApi } from "@/api/Material";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/User";

// mockData
let materialData = ref(["生产物料", "半成品", "其他"]);
let tableData = ref<MaterialResData[]>([]);
let total = ref(0);
let showDatePicker = ref(false);
let loading = ref(false);
const userStore = useUserStore();
let searchData = ref<MaterialSearchData>({
  materialName: "",
  materialType: "",
});
let params = ref<PaginationType>({
  currentPage: 1,
  pageSize: 10,
});
let ifSearch = ref(false);

const filteredSearchData: Partial<MaterialSearchData> = {};
const $router = useRouter();

const handler = (page) => {
  params.value.currentPage = page;
  if (ifSearch.value) {
    getTableData(filteredSearchData);
  } else {
    getTableData();
  }
};
const sizeHandler = (page_size) => {
  params.value.pageSize = page_size;
  if (ifSearch.value) {
    getTableData(filteredSearchData);
  } else {
    getTableData();
  }
};
const getTableData = async (data?) => {
  try {
    loading.value = true;
    const TotalRes = await getMaterialListApi();
    total.value = TotalRes.results.length;
    const res: MaterialListResData = await getMaterialListApi(
      data,
      params.value
    );
    tableData.value = res.results;
    if (ifSearch.value) {
      total.value = res.results.length;
    }
  } catch (err: any) {
    ElMessage({ type: "error", message: err.message });
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getTableData();
});

const gotoAdd = () => {
  $router.push("/material/addMaterial");
};
const gotoDetail = (objectId) => {
  $router.push({
    path: "/material/materialDetail",
    query: { objectId },
  });
};
const editSupplier = (objectId) => {
  $router.push({ path: "/material/editMaterial", query: { objectId } });
};
const reset = () => {
  searchData.value = {
    materialName: "",
    materialType: "",
  };
  params.value.currentPage = 1;
  params.value.pageSize = 10;
  ifSearch.value = false;
  getTableData();
};
const onSearch = () => {
  let allFieldsEmpty = true;
  Object.keys(filteredSearchData).forEach((key) => {
    delete filteredSearchData[key];
  });
  for (const key in searchData.value) {
    if (searchData.value[key] !== "") {
      allFieldsEmpty = false;
      filteredSearchData[key] = searchData.value[key];
    }
  }
  ifSearch.value = !allFieldsEmpty;
  params.value.currentPage = 1;
  params.value.pageSize = 10;
  getTableData(filteredSearchData);
};
const onCancel = async (objectId: string) => {
  try {
    const res: any = await deleteMaterialApi(objectId);
    ElMessage({ type: "success", message: "删除成功" });
    getTableData();
  } catch (err: any) {
    ElMessage({ type: "error", message: err.message });
  }
};
</script>

<template>
  <div style="padding: 20px">
    <el-card>
      <div class="operateContainer">
        <div
          class="formContainer"
          :style="showDatePicker ? 'height:85px' : 'height:32px'"
        >
          <el-form inline :model="searchData">
            <el-form-item prop="returnName">
              <el-input
                placeholder="请输入物料编号/名称"
                style="width: 250px"
                v-model.trim="searchData.materialName"
              ></el-input>
            </el-form-item>
            <el-form-item prop="purchaseName">
              <el-select
                v-model="searchData.materialType"
                placeholder="请选择物料类型"
                style="width: 250px"
              >
                <el-option
                  v-for="item in materialData"
                  :key="item"
                  :value="item"
                  :label="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="searchOperate">
          <div class="button">
            <el-button type="primary" plain style="width: 80px" @click="reset"
              >重置</el-button
            >
            <el-button type="primary" style="width: 80px" @click="onSearch"
              >查询</el-button
            >
          </div>
        </div>
      </div>
    </el-card>
    <el-card style="margin-top: 20px">
      <template #header>
        <span style="font-weight: bold">物料管理</span>
      </template>
      <div class="operate">
        <el-button style="width: 80px" type="primary" @click="gotoAdd"
          >新增</el-button
        >
        <el-button style="width: 80px" type="primary" plain>导入</el-button>
        <el-button style="width: 80px" type="primary" plain>导出</el-button>
      </div>
      <el-table
        :data="tableData"
        style="margin-top: 15px"
        border
        v-loading="loading"
      >
        <el-table-column type="selection" align="center"> </el-table-column>
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="60"
          fixed="left"
        ></el-table-column>
        <el-table-column
          align="center"
          label="物料编号"
          fixed="left"
          prop="materialId"
        >
          <template #="{ row, $index }">
            <el-button link type="primary" @click="gotoDetail(row.objectId)">{{
              row.materialId
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="物料名称"
          fixed="left"
          prop="materialName"
        ></el-table-column>
        <el-table-column
          align="center"
          label="规格型号"
          prop="type"
        ></el-table-column>
        <el-table-column
          align="center"
          label="单位"
          prop="unit"
        ></el-table-column>
        <el-table-column
          align="center"
          label="物料类型"
          prop="materialType"
        ></el-table-column>
        <el-table-column
          align="center"
          label="物料属性"
          prop="materialProp"
        ></el-table-column>
        <el-table-column
          align="center"
          label="库存数量"
          prop="num"
        ></el-table-column>
        <el-table-column
          align="center"
          label="物料分类"
          prop="materialCategory"
        ></el-table-column>
        <el-table-column
          align="center"
          label="状态"
          prop="status"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="200" fixed="right">
          <template #="{ row, $index }">
            <el-button link type="primary" @click="editSupplier(row.objectId)"
              >编辑</el-button
            >
            <el-popconfirm
              title="你确定要删除吗?"
              @confirm="onCancel(row.objectId)"
            >
              <template #reference>
                <el-button link type="primary">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="params.currentPage"
        v-model:page-size="params.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout="prev,pager,next,jumper,->,sizes,total"
        :total="total"
        @current-change="handler"
        @size-change="sizeHandler"
        style="margin-top: 10px"
      ></el-pagination>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.operateContainer {
  display: flex;
  align-content: center;
  justify-content: space-between;
  .formContainer {
    width: 1060px;
    height: 32px;
    transition: height 0.3s ease; // 添加高度变化的过渡效果
    overflow: hidden; // 防止内容溢出
    .el-form-item {
      margin-bottom: 0;
    }
  }
  .searchOperate {
    display: flex;
    align-items: center;
    .more {
      margin-left: 20px;
      display: flex;
      align-items: center;
    }
  }
}

/* 定义旋转动画 */
.rotate-180 {
  transition: transform 0.3s ease;
  transform: rotate(180deg);
}
</style>
